package com.sgu6.netty.handler;


import android.util.Log;

import com.sgu6.netty.protobuffer.NettyMessageProto;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;


public class FinishOrderHandler extends ChannelHandlerAdapter {

    protected final String TAG = FinishOrderHandler.class.getSimpleName();

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Log.i(TAG, "channelActive: ");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessageProto.NettyMessage packet = (NettyMessageProto.NettyMessage) msg;
        if (packet.getHeader() != null && packet.getHeader().getType() == NettyMessageProto.Header.Type.FINISH_ORDER_RESP) {
            NettyMessageProto.Msg returnMsg = packet.getBody().unpack(NettyMessageProto.Msg.class);
            Log.i(TAG, "FinishOrderHandler channelRead: ");
            //if (StringUtils.isNotEmpty(returnMsg.getMsg())) {
            //收到服务器的完结订单回复，将保存在本地的订单信息删除
            //String orderNo = returnMsg.getMsg();
            //Map<String,String> makeRiceResult = new HashMap<>();
            //String content = FileUtils.BufferedReader(ComConstant.resultFilePath);
            //if ("" != content){
            //	makeRiceResult = JsonUtils.toBean(content,HashMap.class);
            //}
            //makeRiceResult.remove(orderNo);
            //FileUtils.writeToFile(ComConstant.resultFilePath,JsonUtils.toJson(makeRiceResult),false);
            //}
        } else {
            ctx.fireChannelRead(msg);
        }


    }

    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) {
        Log.i(TAG, "close: ");
        ctx.close(promise);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Log.i(TAG, "channelInactive: ");
    }

    @Override
    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        ctx.disconnect(promise);
        Log.i(TAG, "disconnect: ");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Log.i(TAG, "exceptionCaught: ");
        Channel channel = ctx.channel();
        cause.printStackTrace();
        if (channel.isActive()) {
            Log.i(TAG, "exceptionCaught: client" + channel.remoteAddress() + "异常");
        }
    }


}
